﻿namespace UnityEditor
{
    using Mono.Cecil;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using UnityEngine;

    public class AssemblyHelper
    {
        private static void AddReferencedAssembliesRecurse(string assemblyPath, List<string> alreadyFoundAssemblies, string[] allAssemblyPaths, string[] foldersToSearch, Dictionary<string, AssemblyDefinition> cache)
        {
            AssemblyDefinition assemblyDefinitionCached = GetAssemblyDefinitionCached(assemblyPath, cache);
            if (assemblyDefinitionCached == null)
            {
                throw new ArgumentException("Referenced Assembly " + Path.GetFileName(assemblyPath) + " could not be found!");
            }
            if (alreadyFoundAssemblies.IndexOf(assemblyPath) == -1)
            {
                alreadyFoundAssemblies.Add(assemblyPath);
                foreach (AssemblyNameReference reference in assemblyDefinitionCached.MainModule.AssemblyReferences)
                {
                    if (reference.Name != "WinRTBridge")
                    {
                        string str = FindAssemblyName(reference.FullName, reference.Name, allAssemblyPaths, foldersToSearch, cache);
                        if (str == string.Empty)
                        {
                            throw new ArgumentException(string.Format("The Assembly {0} is referenced by {1}. But the dll is not allowed to be included or could not be found.", reference.Name, assemblyDefinitionCached.MainModule.Assembly.Name.Name));
                        }
                        AddReferencedAssembliesRecurse(str, alreadyFoundAssemblies, allAssemblyPaths, foldersToSearch, cache);
                    }
                }
            }
        }

        public static void ExtractAllClassesThatInheritMonoBehaviourAndScriptableObject(string path, out string[] classNamesArray, out string[] classNameSpacesArray)
        {
            classNamesArray = null;
            classNameSpacesArray = null;
            List<string> list = new List<string>();
            List<string> list2 = new List<string>();
            AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(path);
            foreach (ModuleDefinition definition2 in assembly.Modules)
            {
                foreach (TypeDefinition definition3 in definition2.Types)
                {
                    TypeReference baseType = definition3.BaseType;
                    if (IsTypeMonoBehaviourOrScriptableObject(assembly, baseType))
                    {
                        list.Add(definition3.Name);
                        list2.Add(definition3.Namespace);
                    }
                }
            }
            classNamesArray = list.ToArray();
            classNameSpacesArray = list2.ToArray();
        }

        public static AssemblyTypeInfoGenerator.ClassInfo[] ExtractAssemblyTypeInfo(string assemblyPathName)
        {
            AssemblyTypeInfoGenerator generator = new AssemblyTypeInfoGenerator(assemblyPathName);
            generator.gatherClassInfo();
            return generator.ClassInfoArray;
        }

        public static string ExtractInternalAssemblyName(string path)
        {
            return AssemblyDefinition.ReadAssembly(path).Name.Name;
        }

        public static string[] FindAssembliesReferencedBy(string path, string[] foldersToSearch)
        {
            return FindAssembliesReferencedBy(new string[] { path }, foldersToSearch);
        }

        public static string[] FindAssembliesReferencedBy(string[] paths, string[] foldersToSearch)
        {
            List<string> alreadyFoundAssemblies = new List<string>();
            string[] allAssemblyPaths = paths;
            Dictionary<string, AssemblyDefinition> cache = new Dictionary<string, AssemblyDefinition>();
            for (int i = 0; i < paths.Length; i++)
            {
                AddReferencedAssembliesRecurse(paths[i], alreadyFoundAssemblies, allAssemblyPaths, foldersToSearch, cache);
            }
            for (int j = 0; j < paths.Length; j++)
            {
                alreadyFoundAssemblies.Remove(paths[j]);
            }
            return alreadyFoundAssemblies.ToArray();
        }

        private static string FindAssemblyName(string fullName, string name, string[] allAssemblyPaths, string[] foldersToSearch, Dictionary<string, AssemblyDefinition> cache)
        {
            for (int i = 0; i < allAssemblyPaths.Length; i++)
            {
                if (GetAssemblyDefinitionCached(allAssemblyPaths[i], cache).MainModule.Assembly.Name.Name == name)
                {
                    return allAssemblyPaths[i];
                }
            }
            foreach (string str in foldersToSearch)
            {
                string path = Path.Combine(str, name + ".dll");
                if (File.Exists(path))
                {
                    return path;
                }
            }
            return string.Empty;
        }

        private static AssemblyDefinition GetAssemblyDefinitionCached(string path, Dictionary<string, AssemblyDefinition> cache)
        {
            if (cache.ContainsKey(path))
            {
                return cache[path];
            }
            AssemblyDefinition definition = AssemblyDefinition.ReadAssembly(path);
            cache[path] = definition;
            return definition;
        }

        public static string[] GetNamesOfAssembliesLoadedInCurrentDomain()
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            List<string> list = new List<string>();
            foreach (Assembly assembly in assemblies)
            {
                try
                {
                    list.Add(assembly.Location);
                }
                catch (NotSupportedException)
                {
                }
            }
            return list.ToArray();
        }

        internal static System.Type[] GetTypesFromAssembly(Assembly assembly)
        {
            try
            {
                return assembly.GetTypes();
            }
            catch (ReflectionTypeLoadException)
            {
                return new System.Type[0];
            }
        }

        private static bool IsTypeMonoBehaviourOrScriptableObject(AssemblyDefinition assembly, TypeReference type)
        {
            if (type != null)
            {
                if (type.FullName == "System.Object")
                {
                    return false;
                }
                Assembly assembly2 = null;
                if (type.Scope.Name == "UnityEngine")
                {
                    assembly2 = typeof(MonoBehaviour).Assembly;
                }
                else if (type.Scope.Name == "UnityEditor")
                {
                    assembly2 = typeof(EditorWindow).Assembly;
                }
                if (assembly2 != null)
                {
                    System.Type type2 = assembly2.GetType(type.FullName);
                    if ((type2 == typeof(MonoBehaviour)) || type2.IsSubclassOf(typeof(MonoBehaviour)))
                    {
                        return true;
                    }
                    if ((type2 == typeof(ScriptableObject)) || type2.IsSubclassOf(typeof(ScriptableObject)))
                    {
                        return true;
                    }
                }
                foreach (ModuleDefinition definition in assembly.Modules)
                {
                    TypeDefinition definition2 = definition.GetType(type.FullName);
                    if (definition2 != null)
                    {
                        return IsTypeMonoBehaviourOrScriptableObject(assembly, definition2.BaseType);
                    }
                }
            }
            return false;
        }
    }
}

